package com.atguigu.gmall.common.util;

import com.atguigu.gmall.common.constant.RedisConst;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO 工具类 利用线程绑定机制  线程绑定的机制 就是以 Map<>集合等方式一对一</>
 */
public class UserAuthUtil {
    /**  TODO    dispatcherServlet-> controller -> service->dao 都是一个线程
     * 获取老请求  拿到客户的临时id 和登录后的id
     * //TODO Springmvc只要开始处理请求，就会自动把当前请求绑定共享到当前线程
     * // TODO  RequestContextHolder 请求保持器
     * @return
     */
    public static HttpServletRequest  request(){
        //TODO 放请求 web-all 接收请求 tomcat服务器放一个请求 servlet机制
        //TODO 请求一结束  tomcat会调用销毁请求 requestDestroyed()
        //TODO 底层以ThreadLocal  SpringMvc随时获取老请求的代码
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return  attributes.getRequest();

    }

    /**
     * 获取userId
     * @return
     */
    public static Long getUserId() {
        HttpServletRequest request = request();
        String header = request.getHeader(RedisConst.USER_ID_HEADER);
        long  userId = Long.parseLong(header);
        return  userId;
    }
}
